package com.sunday.pinxinghui.base;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.pinxinghui.service.LocationService;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.List;

import butterknife.ButterKnife;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;


/**
 * Created by 刘涛 on 2017/8/3.
 */

public abstract class MyBaseActivity extends BaseActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // checkSdCardPermission();
        // checkLocationPermission();
    }

    protected void checkSdCardPermission() {
        RationaleListener rationaleListener = new RationaleListener() {
            @Override
            public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
                AlertDialog.newBuilder(mContext)
                        .setTitle("温馨提示")
                        .setMessage("请开启SD卡读写权限")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                rationale.resume();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        rationale.cancel();
                                    }
                                }
                        ).show();
            }
        };
        AndPermission.with(this)
                .requestCode(100)
                .permission(WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE)
                .rationale(rationaleListener)
                .callback(listener)
                .start();
    }


    protected void checkLocationPermission() {
        RationaleListener rationaleListener = new RationaleListener() {
            @Override
            public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
                AlertDialog.newBuilder(mContext)
                        .setTitle("温馨提示")
                        .setMessage("请开启位置权限")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                rationale.resume();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        rationale.cancel();
                                    }
                                }
                        ).show();
            }
        };
        AndPermission.with(this)
                .requestCode(200)
                .permission(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION)
                .rationale(rationaleListener)
                .callback(listener)
                .start();

    }


    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case 100:
                    if (AndPermission.hasPermission(mContext, WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE)) {
                        onRequestSdSucceed();
                    } else {
                        AndPermission.defaultSettingDialog(mContext)
                                .setTitle("权限申请失败")
                                .setMessage("为确保app正常使用，请在设置中授权")
                                .setPositiveButton("去设置")
                                .show();
                    }
                    break;
                case 200:
                    if (AndPermission.hasPermission(mContext, ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION)) {
                        onRequestLocPermissionSuccessed();
                    } else {
                        AndPermission.defaultSettingDialog(mContext)
                                .setTitle("权限申请失败")
                                .setMessage("为确保app正常使用，请在设置中授权")
                                .setPositiveButton("去设置")
                                .show();
                    }
                    break;
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case 100:
                    if (AndPermission.hasPermission(mContext, WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE)) {
                        onRequestSdSucceed();
                    } else {
                        AndPermission.defaultSettingDialog(mContext)
                                .setTitle("权限申请失败")
                                .setMessage("为确保app正常使用，请在设置中授权")
                                .setPositiveButton("去设置")
                                .show();
                    }
                    break;
                case 200:
                    if (AndPermission.hasPermission(mContext, ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION)) {
                        onRequestLocPermissionSuccessed();
                    } else {
                        AndPermission.defaultSettingDialog(mContext)
                                .setTitle("权限申请失败")
                                .setMessage("为确保app正常使用，请在设置中授权")
                                .setPositiveButton("去设置")
                                .show();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 100:
                if (AndPermission.hasPermission(mContext, WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE)) {
                    onRequestSdSucceed();
                } else {
                    AndPermission.defaultSettingDialog(mContext)
                            .setTitle("SD卡权限申请失败")
                            .setMessage("为确保app正常使用，请在设置中授权")
                            .setPositiveButton("去设置")
                            .show();
                }
                break;
            case 200:
                if (AndPermission.hasPermission(mContext, ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION)) {
                    onRequestLocPermissionSuccessed();
                } else {
                    AndPermission.defaultSettingDialog(mContext)
                            .setTitle("权限申请失败")
                            .setMessage("为确保app正常使用，请在设置中授权")
                            .setPositiveButton("去设置")
                            .show();
                }
                break;
        }

    }

    public abstract void onRequestLocPermissionSuccessed();

    public LocationService locationService;
    private LocationClient mClient;

    public void requestLocation() {
        locationService = BaseApplication.getInstance().getLocationService();
        LocationClientOption mOption = locationService.getDefaultLocationClientOption();
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mOption.setCoorType("bd09ll");
        mClient = new LocationClient(getApplicationContext());
        mClient.setLocOption(mOption);
        mClient.registerLocationListener(locListener);
        mClient.start();
    }

    /***
     * 定位结果回调，在此方法中处理定位结果
     */
    BDLocationListener locListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub

            if (location != null && location.getLocType() != BDLocation.TypeServerError) {
                Log.i(TAG, "定位成功");
                Log.i(TAG, "currentThread" + Thread.currentThread());
                mClient.stop();
                String latitude = String.valueOf(location.getLatitude());
                String longitude = String.valueOf(location.getLongitude());
                SharePerferenceUtils.getIns(getApplicationContext()).putString("latitude", latitude);
                SharePerferenceUtils.getIns(getApplicationContext()).putString("longitude", longitude);
                BaseApplication.getInstance().setCityName(location.getCity());
                BaseApplication.getInstance().setLati(latitude);
                BaseApplication.getInstance().setLongti(longitude);
                onLocSucceed();

            } else {
                onLocFailed();
                ToastUtils.showToast(getApplicationContext(), "定位失败，请开启位置服务后重新定位");
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    };

    public abstract void onLocSucceed();

    public abstract void onLocFailed();

    public abstract void onRequestSdSucceed();


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
